package io.cici.cc.mybatis.lite.sql_source;

import io.cici.cc.mybatis.lite.builder.xml.XmlMapperEntityResolver;
import io.cici.cc.mybatis.lite.executor.parameter.ParameterHandler;
import io.cici.cc.mybatis.lite.mapping.MappedStatement;
import io.cici.cc.mybatis.lite.mapping.Sql;
import io.cici.cc.mybatis.lite.mapping.SqlSource;
import io.cici.cc.mybatis.lite.parse.FixedVariableParser;
import io.cici.cc.mybatis.lite.parse.Node;
import io.cici.cc.mybatis.lite.parse.XPathParser;
import io.cici.cc.mybatis.lite.session.Configuration;
import io.cici.cc.mybatis.lite.sql_source.scripting.LanguageDriver;
import io.cici.cc.mybatis.lite.sql_source.scripting.XMLScriptBuilder;
import io.cici.cc.mybatis.lite.sql_source.scripting.tag.TextTag;


public class XMLLanguageDriver implements LanguageDriver {

    @Override
    public ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, Sql sql) {
        return new DefaultParameterHandler(mappedStatement, parameterObject, sql);
    }

    @Override
    public SqlSource createSqlSource(Configuration configuration, Node node, Class<?> parameterType) {
        XMLScriptBuilder builder = new XMLScriptBuilder(configuration, node, parameterType);
        return builder.parseScriptNode();
    }

    @Override
    public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType) {

        if (script.startsWith("<script>")) {
            XPathParser xPathParser = new XPathParser(script, configuration.getVariables(), false,
                    new XmlMapperEntityResolver());
            return createSqlSource(configuration, xPathParser.evalNode("/script"), parameterType);
        }

        script = FixedVariableParser.parse(script, configuration.getVariables());
        TextTag textTag = new TextTag(script);
        if (textTag.hasVariable()) {
            return new DynamicSqlSource(configuration, textTag);
        } else {
            return new RawSqlSource(configuration, script, parameterType);
        }
    }

}
